package org.feng.utils;

import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.fastjson.JSON;
import org.feng.base.entity.Result;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @author by feng
 * @des redisHash
 * @date 2021/4/27 14:03
 */
public class ExcelUtils {

    public static <T> void writeExcel(HttpServletResponse response, List<T> data, Class<T> entityClass) throws IOException {
        try {
            String fileName = System.currentTimeMillis() + "";
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-disposition", "attachment;filename*=" + fileName + ".xlsx");
            EasyExcelFactory.write(response.getOutputStream(), entityClass).sheet("表格").doWrite(data);
        } catch (IOException e) {
            e.printStackTrace();
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            response.setStatus(500);
            response.getWriter().println(JSON.toJSONString(Result.error("下载失败")));
        }
    }
    public static <T> void writeExcel(HttpServletResponse response, List<T> data, Class<T> entityClass,String fileName) throws IOException {
        try {
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-disposition", "attachment;filename*=" + fileName + ".xlsx");
            EasyExcelFactory.write(response.getOutputStream(), entityClass).sheet("表格").doWrite(data);
        } catch (IOException e) {
            e.printStackTrace();
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            response.setStatus(500);
            response.getWriter().println(JSON.toJSONString(Result.error("下载失败")));
        }
    }
}
